#include <avr/io.h>
#include <avr/iom32.h>

#include <util/delay.h>

#include "Shared.h"
#include "Uart.h"
#include "Icsp.h"

static uint8_t Reply[2];
static uint8_t RxBuff[RX_SIZE];
static uint8_t Invitation[] = "Avr Board";

void Initialize(void);
void WriteIcsp(uint8_t length);
void ReadIcsp(uint8_t length);


int main()
{
	Initialize();
	while(1)
    {
		ReceiveBuffer(RxBuff, 1);
		uint8_t command = RxBuff[0] & 0xF0;
		switch(command)
		{
			case 0x00:
				SendBuffer(RxBuff, 1);
			break;
			case 0x10:
				SetMclr(RxBuff[0]);
				SendBuffer(Reply, 1);
			break;
			case 0x20:
				ClockControlBits(RxBuff[0]);
				SendBuffer(Reply, 1);
			break;
			case 0x30:
				ClockLowXTimes(RxBuff[0]);
				SendBuffer(Reply, 1);
			break;
			case 0x50:
				WriteIcsp(RxBuff[0] & 0x0F);
			break;
			case 0x60:
				ReadIcsp(RxBuff[0] & 0x0F);
			break;
		}
    }
}

void Initialize(void)
{
	Reply[0] = 0x01;
	Reply[1] = 0x00;

	SETBIT(OUT_DDR,MCLR);
	SETBIT(OUT_DDR,PGC);
	SETBIT(OUT_DDR,PGD);
	CLEARBIT(OUT_PORT,MCLR);
	CLEARBIT(OUT_PORT,PGC);
	CLEARBIT(OUT_PORT,PGD);


	InitUart();
	SendBuffer(Invitation, 9);
}

void WriteIcsp(uint8_t length)
{
	if(length > 4)
	{
		SendBuffer(Reply + 1, 1);
		return;
	}

	ReceiveBuffer(RxBuff, length);
	for(uint8_t index = 0; index < length; index++)
	{
		ClockByte(RxBuff[index]);
	}
	SendBuffer(Reply, 1);
}

void ReadIcsp(uint8_t length)
{
	if(length > 4)
	{
		SendBuffer(Reply + 1, 1);
		return;
	}

	for(uint8_t index = 0; index < length; index++)
	{
		PinByte(RxBuff + index);
	}
	SendBuffer(RxBuff, length);
}
